<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div
        class="sidebar-item"
        :class="{ active: currentView === 'import' }"
        @click="currentView = 'import'"
      >
        学生导入
      </div>
      <div
        class="sidebar-item"
        :class="{ active: currentView === 'manage' }"
        @click="currentView = 'manage'"
      >
        学生管理
      </div>
      <div
        class="sidebar-item"
        :class="{ active: currentView === 'scores' }"
        @click="currentView = 'scores'"
      >
        成绩查看
      </div>
      <div class="sidebar-spacer"></div>
      <div
        class="sidebar-item logout"
        @click="handleLogout"
      >
        退出登录
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <header class="main-header">
        <div class="header-left">
          <img src="../assets/cwnu.png" alt="logo" class="header-logo" />
          <span class="header-title">第一届指法大赛 管理员界面</span>
        </div>
      </header>

      <!-- 学生导入视图 -->
      <div v-if="currentView === 'import'" class="content-area">
        <div class="upload-container">
          <div class="upload-box" @click="triggerFileInput">
            <input
              type="file"
              ref="fileInput"
              @change="handleFileChange"
              accept=".xlsx"
              style="display: none"
            />
            <div class="upload-icon">↑</div>
            <div class="upload-text">
              {{ selectedFile ? selectedFile.name : '点击上传.xlsx文件，要求文件名格式：计2024级9班(202413409)' }}
            </div>
          </div>
          <button
            class="upload-button"
            :disabled="!selectedFile"
            @click="uploadFile"
          >
            上传
          </button>
        </div>
      </div>

      <!-- 学生管理视图 -->
      <div v-if="currentView === 'manage'" class="content-area">
        <div class="manage-container">
          <div class="manage-header">
            <button class="add-button" @click="showAddDialog">添加学生</button>
          </div>
          <div class="table-container">
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>姓名</th>
                  <th>学号</th>
                  <th>年级</th>
                  <th>班级</th>
                  <th>性别</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in currentPageData" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.username }}</td>
                  <td>{{ user.grade }}</td>
                  <td>{{ user.clazz }}</td>
                  <td>{{ user.gender }}</td>
                  <td>
                    <button class="edit-button" @click="showEditDialog(user)">编辑</button>
                    <button class="delete-button" @click="handleDelete(user.id)">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="pagination">
            <button
              :disabled="currentPage === 1"
              @click="currentPage--"
            >
              上一页
            </button>
            <span>{{ currentPage }} / {{ totalPages }}</span>
            <button
              :disabled="currentPage === totalPages"
              @click="currentPage++"
            >
              下一页
            </button>
          </div>
        </div>

        <!-- 添加/编辑对话框 -->
        <div class="dialog" v-if="showDialog">
          <div class="dialog-content">
            <h2>{{ isEditing ? '编辑学生' : '添加学生' }}</h2>
            <form @submit.prevent="handleSubmit">
              <div class="form-group">
                <label>姓名：</label>
                <input v-model="formData.name" required />
              </div>
              <div class="form-group">
                <label>学号：</label>
                <input v-model="formData.username" required />
              </div>
              <div class="form-group">
                <label>年级：</label>
                <input v-model="formData.grade" type="number" required />
              </div>
              <div class="form-group">
                <label>班级：</label>
                <input v-model="formData.clazz" type="number" required />
              </div>
              <div class="form-group">
                <label>性别：</label>
                <select v-model="formData.gender" required>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
              <div class="form-group">
                <label>密码：</label>
                <input v-model="formData.password" type="password" required />
              </div>
              <div class="dialog-buttons">
                <button type="submit">确定</button>
                <button type="button" @click="showDialog = false">取消</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 成绩查看视图 -->
      <div v-if="currentView === 'scores'" class="content-area">
        <div class="manage-container">
          <div style="margin-bottom: 16px; text-align: right;">
            <button class="add-button" @click="exportScores">导出</button>
          </div>
          <div class="table-container">
            <table>
              <thead>
                <tr>
                  <th>排名</th>
                  <th>姓名</th>
                  <th>学号</th>
                  <th>年级</th>
                  <th>班级</th>
                  <th>性别</th>
                  <th>正确字符</th>
                  <th>正确率</th>
                  <th>参赛时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(score, index) in currentPageScores" :key="score.id">
                  <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
                  <td>{{ score.user?.name }}</td>
                  <td>{{ score.user?.username }}</td>
                  <td>{{ score.user?.grade }}</td>
                  <td>{{ score.user?.clazz }}</td>
                  <td>{{ score.user?.gender }}</td>
                  <td>{{ score.number }}</td>
                  <td>{{ (score.accuracy * 100).toFixed(2) }}%</td>
                  <td>{{ formatDate(score.createTime) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="pagination">
            <button
              :disabled="currentPage === 1"
              @click="currentPage--"
            >
              上一页
            </button>
            <span>{{ currentPage }} / {{ Math.ceil((scores.length || 0) / pageSize) }}</span>
            <button
              :disabled="currentPage === Math.ceil((scores.length || 0) / pageSize)"
              @click="currentPage++"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const currentView = ref('import')
const fileInput = ref(null)
const selectedFile = ref(null)

// 学生管理相关数据
const users = ref([])
const currentPage = ref(1)
const pageSize = 20
const showDialog = ref(false)
const isEditing = ref(false)
const formData = ref({
  name: '',
  username: '',
  grade: 2024,
  clazz: 1,
  gender: '男',
  password: '123456'
})

// 成绩管理相关数据
const scores = ref([])

// 计算总页数
const totalPages = computed(() => Math.ceil(users.value.length / pageSize))

// 计算当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return users.value.slice(start, end)
})

// 计算当前页成绩数据
const currentPageScores = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return scores.value.slice(start, end)
})

onMounted(async () => {
  // 验证管理员身份
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (!userInfo.isAdmin) {
    router.push('/login')
    return
  }

  // 根据当前视图加载数据
  if (currentView.value === 'manage') {
    await fetchUsers()
  } else if (currentView.value === 'scores') {
    await fetchScores()
  }
})

// 获取学生列表
async function fetchUsers () {
  try {
    const response = await request.get('/users')
    users.value = response.data
  } catch (error) {
    console.error('获取学生列表失败:', error)
    alert('获取学生列表失败')
  }
}

// 显示添加对话框
function showAddDialog () {
  isEditing.value = false
  formData.value = {
    name: '',
    username: '',
    grade: 2024,
    clazz: 1,
    gender: '男',
    password: '123456'
  }
  showDialog.value = true
}

// 显示编辑对话框
function showEditDialog (user) {
  isEditing.value = true
  formData.value = { ...user }
  showDialog.value = true
}

// 处理表单提交
async function handleSubmit () {
  try {
    let response
    if (isEditing.value) {
      response = await request.put('/users', formData.value)
    } else {
      response = await request.post('/users', formData.value)
    }

    if (response.data) {
      alert(isEditing.value ? '编辑成功' : '添加成功')
      showDialog.value = false
      await fetchUsers()
    } else {
      alert(isEditing.value ? '编辑失败' : '添加失败')
    }
  } catch (error) {
    console.error(isEditing.value ? '编辑失败:' : '添加失败:', error)
    alert(isEditing.value ? '编辑失败' : '添加失败')
  }
}

// 处理删除
async function handleDelete (id) {
  if (!confirm('确定要删除这个学生吗？')) return

  try {
    const response = await request.delete(`/users/${id}`)
    if (response.data) {
      alert('删除成功')
      await fetchUsers()
    } else {
      alert('删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败')
  }
}

// 文件上传相关函数
function triggerFileInput () {
  fileInput.value.click()
}

function handleFileChange (event) {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
  }
}

async function uploadFile () {
  if (!selectedFile.value) return

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    const response = await request.post('/users/addUsers', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    console.log('Upload response:', response)
    if (response.status === 200) {
      alert('学生信息导入成功！')
      selectedFile.value = null
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    } else {
      alert(response.data?.message || '导入失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    const errorMessage = error.response?.data?.message || error.message || '上传失败，请检查文件格式或网络连接'
    alert(errorMessage)
  }
}

// 格式化日期
// function formatDate (dateString) {
//   const date = new Date(dateString)
//   return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
// }

function formatDate (dateString) {
  // 只保留 'YYYY-MM-DD HH:MM:SS'，去掉T、毫秒和时区
  return dateString.replace('T', ' ').replace(/\..*/, '').replace(/\+.*$/, '')
}

// 获取所有成绩
async function fetchScores () {
  try {
    const response = await request.get('/scores/order')
    scores.value = response.data
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    alert('获取成绩列表失败')
  }
}

// 监听视图切换
watch(currentView, async (newView) => {
  currentPage.value = 1 // 重置页码
  if (newView === 'manage') {
    await fetchUsers()
  } else if (newView === 'scores') {
    await fetchScores()
  }
})

// 处理登出
function handleLogout () {
  localStorage.removeItem('userInfo')
  router.push('/#')
}

// 导出成绩
function exportScores () {
  window.open('http://localhost:8085/api/scores/export', '_blank')
}
</script>

<style scoped>
.admin-layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #eee;
  padding-top: 64px;
}

.sidebar-item {
  padding: 15px 20px;
  cursor: pointer;
  color: #333;
  transition: all 0.3s;
}

.sidebar-item:hover {
  background-color: #f5f5f5;
  color: #42b983;
}

.sidebar-item.active {
  background-color: #42b983;
  color: white;
}

.main-content {
  flex: 1;
  background-color: #f5f5f5;
}

.main-header {
  position: fixed;
  top: 0;
  left: 200px;
  right: 0;
  height: 64px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #eee;
  z-index: 2;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-logo {
  height: 40px;
  margin-right: 16px;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
}

.content-area {
  padding: 84px 20px 20px;
}

.upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.upload-box {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.upload-box:hover {
  border-color: #42b983;
}

.upload-icon {
  font-size: 40px;
  color: #42b983;
  margin-bottom: 10px;
}

.upload-text {
  color: #666;
  font-size: 16px;
}

.upload-button {
  width: 100%;
  padding: 12px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.upload-button:not(:disabled):hover {
  background: #3aa876;
}

.manage-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.manage-header {
  margin-bottom: 20px;
}

.add-button {
  background: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.table-container {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f5f5f5;
  font-weight: 600;
}

.edit-button, .delete-button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
}

.edit-button {
  background: #42b983;
  color: white;
}

.delete-button {
  background: #ff4949;
  color: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 12px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 400px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.dialog-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-buttons button[type="submit"] {
  background: #42b983;
  color: white;
}

.dialog-buttons button[type="button"] {
  background: #ddd;
}

.sidebar-spacer {
  flex-grow: 1;
}

.sidebar-item.logout {
  color: #ff4949;
  border-top: 1px solid #eee;
}

.sidebar-item.logout:hover {
  background-color: #fff5f5;
  color: #ff4949;
}
</style>
